package porter

import (
	"context"
	"github.com/tidwall/gjson"
	"shop/src/model"
	"shop/src/open/jd"
	"time"
)

var jdClient = jd.NewClient()

type jdTradeFetcher struct {
	store *model.Store
}

func (f *jdTradeFetcher) fetch(startTime time.Time, endTime time.Time, pageNo int, parameter any, hasTotal bool) (any, error) {
	result, err := jdClient.Execute(context.Background(), "jingdong.pop.order.enSearch", jd.Parameters{
		"start_date":  startTime.UnixMilli(),
		"end_date":    endTime.UnixMilli(),
		"order_state": parameter.(string),
		"page":        pageNo,
		"pageSize":    f.pageSize(),
	})
	if err != nil {
		return nil, err
	}
	return result.Get("jingdong_pop_order_enSearch_response.searchorderinfo_result"), nil
}

func (f *jdTradeFetcher) hasTotal() bool {
	return false
}

func (f *jdTradeFetcher) count(resp any) int {
	result := resp.(gjson.Result)
	return int(result.Get("orderTotal").Int())
}

func (f *jdTradeFetcher) buildDocument(resp any) []model.Document {
	result := resp.(gjson.Result)
	list := result.Get("orderInfoList").Array()
	documents := make([]model.Document, len(list))
	for _, it := range list {
		var document model.Document
		document.Sn = it.Get("orderId").String()
		document.Doc = it.String()
		documents = append(documents, document)
	}
	return documents
}

func (f *jdTradeFetcher) pageSize() int {
	return 100
}

func (f *jdTradeFetcher) startPage() int {
	return 1
}

func (f *jdTradeFetcher) parameters() []any {
	return []any{1}
}

type jdRefundFetcher struct {
	store *model.Store
}

func (f *jdRefundFetcher) fetch(startTime time.Time, endTime time.Time, pageNo int, _ any, _ bool) (any, error) {
	result, err := jdClient.Execute(context.Background(), "jingdong.pop.afs.soa.refundapply.queryPageList", jd.Parameters{
		"applyTimeStart": startTime.UnixMilli(),
		"applyTimeEnd":   endTime.UnixMilli(),
		"pageIndex":      pageNo,
		"pageSize":       f.pageSize(),
	})
	if err != nil {
		return nil, err
	}
	return result.Get("jingdong_pop_afs_soa_refundapply_queryPageList_response.queryResult"), nil
}

func (f *jdRefundFetcher) hasTotal() bool {
	return false
}

func (f *jdRefundFetcher) count(resp any) int {
	result := resp.(gjson.Result)
	return int(result.Get("totalCount").Int())
}

func (f *jdRefundFetcher) buildDocument(resp any) []model.Document {
	result := resp.(gjson.Result)
	list := result.Get("result").Array()
	documents := make([]model.Document, len(list))
	for _, it := range list {
		var document model.Document
		document.Sn = it.Get("orderId").String()
		document.Rsn = it.Get("id").String()
		document.Doc = it.String()
		documents = append(documents, document)
	}
	return documents
}

func (f *jdRefundFetcher) pageSize() int {
	return 100
}

func (f *jdRefundFetcher) startPage() int {
	return 1
}

func (f *jdRefundFetcher) parameters() []any {
	return []any{1}
}
